<template>
  <view class="container-main">
    <!-- 添加收货地址 -->
    <view class="addAddress" v-if="JSON.stringify(defaultAddress) == '{}'" @click="chooseUserAddress">
      <view class="text">
        请添加收货地址
      </view>
      <uni-icons type="forward" color="#9BA3AA"></uni-icons>
    </view>
    <!-- 展示收货地址处 -->
    <view class="deliveryAddress" v-else>
      <view class="address-item">
        <view class="left">
          <view class="name">
            {{defaultAddress.name}} {{defaultAddress.phone}}
          </view>
          <view class="address">
            {{defaultAddress.region}}{{defaultAddress.street}}
          </view>
        </view>
        <view class="right" @click="amendAddress">
          <uni-icons type="bars" size="30"></uni-icons>
        </view>
      </view>
    </view>
    <!-- 详情页过来的商品展示处 -->
    <view class="goodsList" v-if="buyCarGoodsInfo.length == 0">
      <uni-swipe-action>
        <!-- <block v-for="(goods,index) in cart" :key="index"> -->
        <uni-swipe-action-item :right-options="Newoptions" @click="deleteGoods">
          <view class="goods-item">
            <!-- 商品左侧图片区域 -->
            <view class="goods-item-left">
              <image :src="imgPrefixAddress + goodsInfo.goodsPic[0]" class="goods-pic"></image>
            </view>
            <!-- 商品右侧信息区域 -->
            <view class="goods-item-right">
              <!-- 商品标题 -->
              <view class="goods-name">{{goodsInfo.goodsName}}</view>
              <!-- 商品规格 -->
              <view class="goods-specification">
                {{goodsInfo.goodsGuige}}
              </view>
              <view class="goods-info-box">
                <!-- 商品价格 -->
                <view class="goods-price">￥{{totalPrice}}</view>
                <!-- 商品数量 -->
                <uni-number-box :min="1" v-model="goodsNum"></uni-number-box>
              </view>
            </view>
          </view>
        </uni-swipe-action-item>
        <!-- </block> -->
      </uni-swipe-action>
    </view>
    <!-- 购物车过来过来的商品展示处 -->
    <view class="goodsList" v-else>
      <uni-swipe-action>
        <uni-swipe-action-item :right-options="Newoptions" @click="deleteGoods">
          <view class="goods-item" v-for="(item,index) in buyCarGoodsInfo" :key="index">
            <!-- 商品左侧图片区域 -->
            <view class="goods-item-left">
              <image :src="imgPrefixAddress +item.goodsPreviews.split(',')[0]" class="goods-pic"></image>
            </view>
            <!-- 商品右侧信息区域 -->
            <view class="goods-item-right">
              <!-- 商品标题 -->
              <view class="goods-name">{{item.goodsName}}</view>
              <view class="goods-info-box">
                <!-- 商品价格 -->
                <view class="goods-price">￥{{item.retailValue}}</view>
                <!-- 商品数量 -->
                <uni-number-box :min="1" v-model="item.amount"></uni-number-box>
              </view>
            </view>
          </view>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </view>

    <!-- 到货时间 配送相关 -->
    <view class="distribution">
      <!-- 预计到货时间 -->
      <view class="time">
        <view class="time-left">
          <view class="big">
            预计到货时间
          </view>
          <view class="small">
            延期发货最多支持30天
          </view>
        </view>
        <view class="time-right">
          （请选择发货时间） 默认立即发货
          <uni-icons type="right"></uni-icons>
        </view>
      </view>
      <!-- 配送 -->
      <view class="peisong">
        <view class="left">
          配送
        </view>
        <view class="right">
          物流配送 快递{{defaultFreight || freightSum}}元
        </view>
      </view>
    </view>
    <view class="oders">
      <view>
        <text>商品金额：</text>
        <text>¥{{totalPrice || buyCartotalPrices}}</text>
      </view>
      <view>
        <text>配送费：</text>
        <text>¥{{defaultFreight || freightSum}}</text>
      </view>
      <view>
        <text>员工优惠：</text>
        <text>-¥0</text>
      </view>
    </view>
    <view class="jiesuan-button" @click="jiesuan">
      立即支付
    </view>
    <van-dialog id="van-dialog" />
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import Dialog from '@/wxcomponents/@vant/weapp/dialog/dialog';
  export default {
    data() {
      return {
        buyCargoodsNum0: '',
        buyCargoodsNum1: '',
        freightSum: 0,
        // 确认支付弹出层
        isShow: true,
        // 待支付总价
        allSumPrice: 0,
        // 默认total总价
        totalPrice: 0,
        // 默认运费
        defaultFreight: 0,
        //商品详情监听后的运费对象
        watchFreight: 0,
        // 购物车监听的运费对象
        buyCarWatchFreight: {},
        // 需要购买的商品数量
        goodsNum: 1,
        // 商品详情页传递过来的数据
        goodsInfo: {},
        // 购物车传递过来的数据
        buyCarGoodsInfo: [],
        // 传递过来的商品数据保存下来，进行判断
        ifdata: null,
        // 默认地址展示
        defaultAddress: {},
        // 当前选择的收货地址
        choosedAddress: {},
        imgPrefixAddress: "https://bjlr-1316909348.cos.ap-chengdu.myqcloud.com",
        // pop弹出层开关
        show: false,
        Newoptions: [{
          text: '删除',
          style: {
            backgroundColor: '#B8C1CC'
          }
        }],
        // cart: [],
        // 用户地址列表
        userAddress: [],
        // 购物车页面过来传递的数组
        cart: []
      };
    },
    methods: {
      ...mapMutations('m_user', ['updateAddress']),
      otherFun(object) {
        if (object) {
          this.defaultAddress = object
        }
      },
      // 结算
      jiesuan() {
        const that = this
        if (JSON.stringify(this.defaultAddress) == '{}') return uni.$showMsg('请选择收货地址')
        if (that.defaultFreight) {
          Dialog.confirm({
              message: `确认支付吗，包含运费价格：${that.totalPrice + that.defaultFreight}`,
            }).then(() => {
              const jiesuan = {
                openid: 'o7Qwa5JdbngEey8Ls1xGCrKAVsrk',
                order: {
                  amountS: 999,
                  freight: 1,
                  paymentAmountS: 1000

                },
                orders: [{
                  goodsId: 33,
                  sonId: 22,
                  number: 1,
                  salesPrice: 999,
                  consigneeName: '老师的',
                  consigneePhone: '13712319531',
                  consigneeRegion: '四川省成都市武侯区',
                  consigneeLocation: '幸福街道小区'
                }]
              };
              this.ceshi() //获取证书
              this.jiesuanBuy(jiesuan) // 给后端发订单信息
            })
            .catch(() => {
              return uni.$showMsg('您取消了支付')
            });
        } else {
          console.log('为零，从购物车来的');
          Dialog.confirm({
              message: `确认支付吗，包含运费价格：${(that.buyCartotalPrices - 0) + (that.freightSum - 0)}`,
            }).then(() => {
              let arr = []
              that.cart.forEach(item => {
                arr.push(item.cartId)
              })
              let jiesuan = {
                openid: 'o7Qwa5JdbngEey8Ls1xGCrKAVsrk',
                totalMoney: (that.buyCartotalPrices - 0) + (that.freightSum - 0),
                freight: that.freightSum - 0,
                addressId: that.defaultAddress.addressId,
                cartList: arr
              };
              this.jiesuanBuyCar(jiesuan)
            })
            .catch(() => {
              return uni.$showMsg('您取消了支付')
            });
        }

      },
      // 从购物车过来的结算
      async jiesuanBuyCar(obj) {
        const res = await uni.$http.post('/flow/cart/clearing', obj)
        if (res.data.code !== 200) return uni.$showMsg('请求失败，请重试')
        const payObj = {
          timeStamp: res.data.data.timeStamp,
          nonceStr: res.data.data.nonceStr,
          package: res.data.data.package,
          paySign: res.data.data.paySign,
          signType: res.data.data.signType,
          orderNumber: res.data.data.orderNumber
        }
        this.wxpay(payObj)
      },
      // 获取证书
      async ceshi() {
        const res = await uni.$http.get('/flow/order/getMchSerialNo')
      },
      // 立即购买
      async jiesuanBuy(data) {
        const res = await uni.$http.post('/flow/checkout', data)
        if (res.data.code !== 200) return uni.$showMsg('请求失败')
        // 发起微信支付
        const payObj = {
          timeStamp: res.data.data.timeStamp + '',
          nonceStr: res.data.data.nonceStr + '',
          package: res.data.data.package + '',
          paySign: res.data.data.paySign + '',
          signType: res.data.data.signType + '',
          orderNumber: res.data.data.orderNumber
        }
        // 向微信发起支付
        this.wxpay(payObj)
      },
      // 微信支付
      async wxpay(payInfo) {

        await uni.requestPayment({
          nonceStr: payInfo.nonceStr,
          timeStamp: payInfo.timeStamp,
          package: payInfo.package,
          paySign: payInfo.paySign,
          signType: payInfo.signType,
          orderNumber: payInfo.orderNumber,
          success() {
            uni.$http.post('/flow/pay/callback', {
              orderNumber: payInfo.orderNumber,
              timeStamp: payInfo.timeStamp + '',
              nonceStr: payInfo.nonceStr + '',
              package: payInfo.package + '',
              paySign: payInfo.paySign + '',
              signType: payInfo.signType + ''
            })
            uni.$http.post('/flow/cart/payment', {
              cyclotron: '1',
              orderNumber: payInfo.orderNumber,
            })
            uni.$showMsg('支付成功')
            setTimeout(() => {
              uni.redirectTo({
                url: '/subpkg/customerOrders/customerOrders'
              })
            }, 1500)
          },
          fail() {
            uni.$http.post('/flow/pay/callback', {
              // orderNumber: payInfo.orderNumber,
              timeStamp: payInfo.timeStamp + '',
              nonceStr: payInfo.nonceStr + '',
              package: payInfo.package + '',
              paySign: payInfo.paySign + '',
              signType: payInfo.signType + ''
            })
            //  支付失败跳转到商品详情页
            uni.$showMsg('您取消了支付')
            uni.navigateBack()
          }
        })
      },
      // 选择 收货地址
      chooseUserAddress() {
        uni.navigateTo({
          url: '/subpkg/buyNowAddressList/buyNowAddressList'
        })
      },
      //  修改收货地址
      amendAddress(addressData) {
        uni.navigateTo({
          url: '/subpkg/addressList/addressList'
        })
      },
      //删除商品
      async deleteGoods(goods) {
        const params = {
          cartId: goods.cartId
        }
        const res = await uni.$http.post('/flow/cart/remove', params)
        if (res.data.code !== 200) return uni.$showMsg('删除失败')
        this.getUserCarCount()
      },
      // updateBuyCarCount点击修改购物车数量
      async updateBuyCarCount(obj) {
        const res = await uni.$http.post('/flow/cart/quantitychange', obj)
        if (res.data.code !== 200) return uni.$showMsg('修改失败')
      },
      open() {},
      close() {
        this.show = false
      },
      // 获取用户购物车信息
      async getUserCarCount() {
        let res = await uni.$http.get('/flow/cart/list')
        this.cart = res.data.data
      },
      // 获取运费
      async getGoodsFreight(sonId, addressId) {
        const res = await uni.$http.post('/main/freight', {
          sonId: sonId + '',
          addressId: addressId + ''
        })
        if (res.data.code !== 200) return uni.$showMsg('获取运费失败，请重试')
        console.log(res);
        this.defaultFreight = res.data.data
        this.watchFreight = res.data.data
      },
      // 获取当前用户所有地址信息
      async getUserAddress() {
        const res = await uni.$http.get('/personalcenter/address')
        if (res.data.code !== 200) return uni.$showMsg('获取用户收货地址信息失败')
        if (res.data.data.find(item => {
            return item.defaults == '0'
          })) {
          this.defaultAddress = res.data.data.find(item => {
            return item.defaults == '0'
          })
        } else {
          this.defaultAddress = {}
        }
      },
      // 获取购物车所有运费
      async getAllBuyCarFreight(obj) {
        const res = await uni.$http.post('/flow/cart/query/shipping', obj)
        if (res.data.code !== 200) return uni.$showMsg('获取运费失败请重试')
        console.log(res);
        this.freightSum = res.data.data.freightSum
        this.buyCarWatchFreight = res.data.data
      }
    },
    onLoad(options) {
      //获取当前用户购物车数据
      this.getUserCarCount();
      // 获取当前用户默认地址信息
      this.getUserAddress();
      let that = this
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.on('acceptDataFromOpenerPage', function(data) {
        that.ifdata = data
      });
    },
    onShow() {
      this.otherFun() // 获取navigiteBack传递过来的数据
      this.$nextTick(() => {
        if (Array.isArray(this.ifdata)) {
          // 传的数组，从购物车过来的
          this.buyCarGoodsInfo = this.ifdata
          setTimeout(() => {
            let buyCarFreight = {
              addressId: this.defaultAddress.addressId,
              cartlist: this.buyCarGoodsInfo
            }
            this.getAllBuyCarFreight(buyCarFreight)
          }, 500)
        } else {
          // 传的对象，从商品详情页过来的
          this.$nextTick(() => {
            this.goodsInfo = this.ifdata
            this.totalPrice = this.ifdata.goodsPrice
            this.allSumPrice = this.ifdata.goodsPrice
            setTimeout(() => {
              if (JSON.stringify(this.defaultAddress) == '{}') {
                console.log('地址为空的请求运费');
                this.getGoodsFreight(this.goodsInfo.sonId, '')
              } else {
                console.log('地址不为空的请求运费');
                this.getGoodsFreight(this.goodsInfo.sonId, this.defaultAddress.addressId)
              }
            }, 500)
          })
        }
      })
    },
    computed: {
      ...mapState('m_user', ['address']),
      buyCartotalPrices() {
        return this.buyCarGoodsInfo.reduce((acc, item) => acc + item.retailValue * item.amount, 0)
      }
    },
    watch: {
      goodsNum: {
        handler(newVal, oldVal) {
          this.totalPrice = newVal * this.goodsInfo.goodsPrice
          this.defaultFreight = newVal * this.watchFreight
        },
        immediate: true
      },
      buyCarGoodsInfo: {
        handler(newVal, oldVal) {
          uni.$showMsg('运费计算中', 1000)
          setTimeout(() => {
            let allSum = 0
            newVal.forEach(item => {
              allSum += this.buyCarWatchFreight[item.goodsId] * item.amount
            })
            this.freightSum = allSum
          }, 1000)
        },
        deep: true,
      }
    },
  }
</script>

<style lang="scss">
  page {
    background-color: #F5F6F9;
  }

  .addAddress {
    margin-bottom: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 44px;
    background-color: #FFFFFF;
    padding: 0 16px;

    .text {
      font-size: 14px;
      color: #000000;
    }
  }

  // 商品item
  .goodsList {
    background-color: white;
    padding: 0 16px;
    margin-bottom: 20rpx;

    .goods-item {
      display: flex;
      padding: 10px 5px;
      border-bottom: 1px solid #f0f0f0;

      .goods-item-left {
        margin-right: 5px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .goods-pic {
          width: 100px;
          height: 100px;
          display: block;
        }
      }

      .goods-item-right {
        display: flex;
        flex: 1;
        flex-direction: column;
        justify-content: space-between;

        .goods-info-box {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .goods-name {
          font-size: 14px;
          color: #66737F;
        }

        .goods-specification {
          font-size: 10px;
          color: #8F9CA9;
        }

        .goods-price {
          font-size: 14px;
          color: #141414;
        }
      }
    }
  }

  .distribution {
    padding: 0 16px;
    background-color: white;

    .time {
      display: flex;
      justify-content: space-between;
      margin-bottom: 30rpx;
      border-bottom: 1px solid #8F9CA9;
      height: 50px;


      .time-left {
        .big {
          font-size: 14px;
          color: #141414;
        }

        .small {
          font-size: 11px;
          color: #141414;
        }
      }

      .time-right {
        font-size: 14px;
        color: #141414;
        height: 10px;
        line-height: 10px;
      }
    }

    .peisong {
      margin-bottom: 30rpx;
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #141414;
      border-bottom: 1px solid #8F9CA9;
      height: 45px;
      line-height: 45px;
      text-align: center;

      .left {}

      .right {}
    }

    .fapiao {
      margin-bottom: 30rpx;
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #141414;
      height: 45px;
      line-height: 45px;
      text-align: center;

      .left {}

      .right {}
    }
  }

  .oders {
    padding: 0 16px;
    background-color: white;

    view {
      display: flex;
      justify-content: space-between;
      color: #141414;
      font-size: 14px;
      height: 34px;
      line-height: 34px;
      margin-bottom: 10rpx;
    }
  }

  .jiesuan {
    display: flex;
    justify-content: center;

    view {
      background-color: #000000;
      width: 325px;
      height: 36px;
      color: white;
      border-radius: 14px;
      line-height: 36px;
      text-align: center;
    }
  }

  // .container-main {
  //   padding-bottom: 50px;

  // }

  .address-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    padding: 10px;

    .left {
      width: 240px;

      .name {
        font-size: 18px;
        color: #000000;
        margin-bottom: 20rpx;
      }

      .address {
        font-size: 14px;
        color: #8F9CA9;
        word-wrap: break-word;
      }
    }
  }

  .jiesuan-button {
    width: 200px;
    height: 50px;
    margin: 30px auto;
    text-align: center;
    line-height: 50px;
    background-color: #000000;
    color: white;
    border-radius: 30px;
  }
</style>